package org.sojex.photo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.sojex.R;
import org.sojex.photo.bean.CookBook;
import org.sojex.photo.bean.Cooks;
import org.sojex.photo.data.DataAction;
import org.sojex.photo.manage.DBManager;
import org.sojex.photo.manage.SdcardManager;
import org.sojex.photo.util.GlobalData;
import org.sojex.photo.util.Util;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Browser.BookmarkColumns;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class PhotoGridActivity extends Activity {

	/** Called when the activity is first created. */
	GridView gv;
	Adapter adapter;
	Holder holder;
	ProgressDialog progress;// 进度对话框
	DBManager db;// 数据库
	List<String> urlList = new ArrayList<String>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_grid);
		db = DBManager.open(this);
		
		if (!SdcardManager.isSDCardAvailable()) {
			Builder b = new Builder(PhotoGridActivity.this);
			b.setCancelable(false);
			b.setTitle("Error!").setMessage("SD卡不可用！").setPositiveButton("退出", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					finish();
				}
			}).show();
			return;
		} else {
			showProgress();
			File file = new File(GlobalData.pictureBasePath);
			System.out.println("file exists" + file.exists());
			if (file.exists()) {
				getDatafromDB();
			} else {
				initData();
			}

			gv = (GridView) findViewById(R.id.GridView01);
			gv.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					System.out.println(position);
					Intent i = new Intent(getApplicationContext(),
							GalleryActivity.class);
					Bundle b = new Bundle();
					b.putInt("position", position);
					i.putExtras(b);
					startActivity(i);
				}
			});
		}
	}

	// 读取数据库缓存
	public void getDatafromDB() {
		try{
		CookBook cookBook = new CookBook();
		Cursor cursor = db.getCache(cookBook.id() + "");
		if (cursor != null && cursor.moveToFirst()) {
			cookBook = CookBook.StringToBean(cursor.getString(cursor
					.getColumnIndex("content")));
			GlobalData.cookBook = cookBook.cookBook;
			initCateImage(cookBook);
			Message msg = new Message();
			msg.what = Util.INITSUCCESS;
			msg.obj = msg.toString();
			handler.sendMessage(msg);
		} else {
			Message msg = new Message();
			msg.what = Util.INITFAIL;
			msg.obj = msg.toString();
			handler.sendMessage(msg);
		}
		cursor.close();
		}catch(Exception e){
			e.printStackTrace();
			Message msg = new Message();
			msg.what = Util.INITFAIL;
			msg.obj = msg.toString();
			handler.sendMessage(msg);
		}
	}

	public void initCateImage(CookBook cookBook) {
		for (Cooks cooks : cookBook.cookBook) {
			GlobalData.ImageUri.put(cooks.cooksName, GlobalData.pictureBasePath
					+ cooks.cooksName + ".png");
		}
	}
	//显示加载对话框
	public void showProgress() {
		progress = new ProgressDialog(PhotoGridActivity.this);
		progress.setTitle("更新数据");
		progress.setMessage("更新数据");
		progress.show();
	}

	private void initData() {
		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					new DataAction(handler, GlobalData.URL,
							getApplicationContext());
				} catch (Exception e) {
					Message msg = new Message();
					msg.what = DataAction.ERR;
					msg.obj = e.toString();
					handler.sendMessage(msg);
				}
			}
		}.start();
	}

	private void downImage(CookBook cookBook) {
		for (Cooks cooks : cookBook.cookBook) {
			System.out.println("cookBook URL" + cooks.cooksUrl);
			String url = cooks.cooksUrl;
			cooks.cooksPath =  GlobalData.pictureBasePath
			+ cooks.cooksName + ".png";
			if (url != null & !url.equals("")) {
				System.out.println("cookBook in downImage");
				Util.DownImage(this, url, GlobalData.pictureBasePath
						+ cooks.cooksName + ".png", cooks.cooksName, handler);
			}
		}
	}
	public void setURL(){
		ArrayList<Cooks> cookBook = GlobalData.cookBook;
		for(int i=0;i<cookBook.size();i++){
			Cooks cook = cookBook.get(i);
			cook.cooksPath = GlobalData.pictureBasePath
			+ cook.cooksName + ".png";
			GlobalData.cookBook.set(i, cook);
		}
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DataAction.NET_RST:
				progress.dismiss();
				setURL();
				downImage((CookBook) msg.obj);
				adapter = new Adapter();
				gv.setAdapter(adapter);
				break;
			case DataAction.ERR:
				progress.dismiss();
				Builder b = new Builder(PhotoGridActivity.this);
				b.setTitle("Error!").setMessage("初始化失败！无网络连接")
						.setPositiveButton("确定", new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								finish();
							}
						}).show();
				break;
			case Util.INITSUCCESS:
				progress.dismiss();
				adapter = new Adapter();
				gv.setAdapter(adapter);
				break;
			case Util.INITFAIL:
				progress.dismiss();
				Builder b1 = new Builder(PhotoGridActivity.this);
				b1.setTitle("Error!").setMessage("初始化失败！请手动刷新")
						.setPositiveButton("确定", new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
							}
						}).show();
				break;
			case Util.DOWNSUCCESS:
				adapter.notifyDataSetChanged();
				break;
			case Util.DOWNFAIL:
				progress.dismiss();
				Builder b2 = new Builder(PhotoGridActivity.this);
				b2.setTitle("Error!").setMessage(msg.obj.toString()).show();
				break;
			}
		};
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 0, 0, "刷新");
		menu.add(0, 1, 0, "菜单");
		return super.onCreateOptionsMenu(menu);
	}
	

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()){
		case 0:
			System.out.println("menu on click");
			progress.show();
			initData();
			break;
		case 1:
			Intent intent = new Intent(this,MenuListActivity.class);
			startActivity(intent);
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK){
			MyMenu.getInstance(this).destory();
			}
		return super.onKeyDown(keyCode, event);
	}

	protected void onDestroy() {
		super.onDestroy();
		db.close();
	};

	class Holder {
		ImageView head;
		TextView name;
	}

	public Holder initHolder(View v) {
		holder = new Holder();
		holder.head = (ImageView) v.findViewById(R.id.loadimage_row_ImageView);
		holder.name = (TextView) v.findViewById(R.id.loadimage_row_TextView01);
		return holder;
	}

	class Adapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return GlobalData.cookBook.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			LayoutInflater inflater = LayoutInflater
					.from(PhotoGridActivity.this);
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.home_grid_row, null);
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}
			holder = initHolder(convertView);// 初始化控件

		String str = GlobalData.cookBook.get(position).cooksPath;
		if(str!=null&&!str.equals("")){
		if(Util.isExist(str))
			holder.head.setBackgroundDrawable(Drawable.createFromPath(str));
		else
			holder.head.setBackgroundDrawable(getResources().getDrawable(R.drawable.pic));
		}else
			holder.head.setBackgroundDrawable(getResources().getDrawable(R.drawable.pic));
			holder.name.setText(GlobalData.cookBook.get(position).cooksName);
			return convertView;
		}

		public Drawable findDraw(String str) {
			if (GlobalData.ImageUri.get(str) != null) {
				File file = new File(GlobalData.ImageUri.get(str));
				if (file.exists())
					return Drawable.createFromPath(GlobalData.ImageUri.get(str));
				else{
					return getResources().getDrawable(R.drawable.pic);
				}
			} else {
				return getResources().getDrawable(R.drawable.pic);
			}

		}
	}
	
}